package com.xs.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * projectName:MyBatis_01-9_23
 * author:xiaoshun
 * time:2024/9/23 下午4:13
 * description:工具类
 */
public class MyBatisUtils {
    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory=new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession openSession(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession==null){
            sqlSession=factory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
    }

    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
    }

    public static void close(){
        SqlSession sqlSession = openSession();
        sqlSession.close();
        threadLocal.remove();
    }

    public static <T> T getMaaper(Class<T> clazz){
        SqlSession sqlSession = openSession();
        return sqlSession.getMapper(clazz);
    }
}
